package com.vilynn.interview.huawei.nowcoder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 华为面试题1
 */
public class Interview1 {

    public static void main(String[] args) {
        int x = 1;
        int y = 8;
        int z = 4;
        int result = find(x, y , z);
        System.out.println(result);
    }

    /**
     * 2\5对应，6\9对应
     * @param x
     * @param y
     * @param z
     * @return
     */
    private static int find(int x, int y, int z) {
        if (!check(x, y , z)) {
            return -1;
        }
        List<Integer> list = new ArrayList<Integer>();

        int[] arrays = turn(x, y, z);

        sort(arrays);

        int length = arrays.length;

        for (int i = 0; i < length; i++) {
            list.add(arrays[i]);
            if (list.size() >= y) {
                return list.get(y-1);
            }
            for (int j = 0; j < length; j++) {
                if (i != j) {
                    list.add(Integer.parseInt(arrays[i] + "" + arrays[j]));
                    if (list.size() >= y) {
                        return list.get(y-1);
                    }
                }
                for (int k = 0; k < length; k++) {
                    if (i != j && j != k && k != i) {
                        String s = arrays[i] + "" + arrays[j] + "" + arrays[k];
                        list.add(Integer.parseInt(s));
                        if (list.size() >= y) {
                            return list.get(y-1);
                        }
                    }
                }
            }
        }

        return list.size() < y ? list.get(list.size() - 1) : list.get(y-1);
    }

    private static void sort(int[] arrays) {
        for (int i = 0; i < arrays.length; i++) {
            for (int j = i+1; j < arrays.length; j++) {
                if (arrays[j] < arrays[i]) {
                    int temp = arrays[j];
                    arrays[j] = arrays[i];
                    arrays[i] = temp;
                }
            }
        }
    }

    private static boolean check(int x, int y, int z) {
        List<Integer> arrays = Arrays.asList(x,y,z);
        if (arrays.contains(2) && arrays.contains(5)) {
            return false;
        }
        if (arrays.contains(6) && arrays.contains(9)) {
            return false;
        }
        return true;
    }

    private static int[] turn(int x, int y, int z) {
        List<Integer> arrays = Arrays.asList(x,y,z);
        if (arrays.contains(2)) {
            return new int[]{x, y, z, 5};
        }
        if (arrays.contains(5)) {
            return new int[]{x, y, z, 2};
        }
        if (arrays.contains(6)) {
            return new int[]{x, y, z, 9};
        }
        if (arrays.contains(9)) {
            return new int[]{x, y, z, 6};
        }
        return new int[]{x, y, z};
    }
}
